refactor(rag): extract the rag cluster into src/lib/rag/ (maturity X2)#994
Conversation
…r change) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019Jc1ZYHFjXjn6mE6U6riVU
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019Jc1ZYHFjXjn6mE6U6riVU
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThis PR moves RAG modules under ChangesRAG domain-directory extraction
Estimated code review effort: 3 (Moderate) | ~30 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/lib/rag/rag-query-guard.ts (1)
19-34: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate decision tree between the two exported guards.
shouldShortCircuitUnsupportedSearchandisUnsupportedSoftTailAnalysisrun the identical 4-condition chain, only inverting the first two branches' return value. Any change to the pattern guards must be mirrored in both functions with reversed polarity, which is easy to get wrong.♻️ Suggested extraction of the shared classification
+type UnsupportedSearchClassification = + | "pattern_guard" + | "soft_tail_ineligible" + | "soft_tail_consumer" + | "soft_tail_confidence_gate_pass" + | "soft_tail_confidence_gate_fail"; + +function classifyUnsupportedSearch(query: string, analysis: ClinicalQueryAnalysis): UnsupportedSearchClassification { + if (unavailableDocumentNoisePattern.test(query)) return "pattern_guard"; + if (clearlyOutsideCorpusMedicalPattern.test(query) && analysis.documentTitleTerms.length === 0) return "pattern_guard"; + if (!unsupportedSoftTailEligible(analysis)) return "soft_tail_ineligible"; + if (clearlyNonClinicalConsumerPattern.test(query)) return "soft_tail_consumer"; + return analysis.confidence <= 0.42 && analysis.expandedTerms.length <= 5 + ? "soft_tail_confidence_gate_pass" + : "soft_tail_confidence_gate_fail"; +} + export function shouldShortCircuitUnsupportedSearch(query: string, analysis: ClinicalQueryAnalysis) { - if (unavailableDocumentNoisePattern.test(query)) return true; - if (clearlyOutsideCorpusMedicalPattern.test(query) && analysis.documentTitleTerms.length === 0) return true; - if (!unsupportedSoftTailEligible(analysis)) return false; - if (clearlyNonClinicalConsumerPattern.test(query)) return true; - return analysis.confidence <= 0.42 && analysis.expandedTerms.length <= 5; + const classification = classifyUnsupportedSearch(query, analysis); + return classification === "pattern_guard" || classification === "soft_tail_consumer" || classification === "soft_tail_confidence_gate_pass"; } // True only for queries that would short-circuit via the soft tail itself, not a pattern guard. export function isUnsupportedSoftTailAnalysis(query: string, analysis: ClinicalQueryAnalysis) { - if (unavailableDocumentNoisePattern.test(query)) return false; - if (clearlyOutsideCorpusMedicalPattern.test(query) && analysis.documentTitleTerms.length === 0) return false; - if (!unsupportedSoftTailEligible(analysis)) return false; - if (clearlyNonClinicalConsumerPattern.test(query)) return false; - return analysis.confidence <= 0.42 && analysis.expandedTerms.length <= 5; + return classifyUnsupportedSearch(query, analysis) === "soft_tail_confidence_gate_pass"; }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/lib/rag/rag-query-guard.ts` around lines 19 - 34, Extract the shared classification logic from shouldShortCircuitUnsupportedSearch and isUnsupportedSoftTailAnalysis into a single private helper that distinguishes pattern-guard matches from soft-tail eligibility. Update both exported functions to reuse that helper while preserving their current behavior: the first should short-circuit on any guard or soft-tail match, and the second should return true only for the soft-tail match.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/clinical-hazard-analysis.md`:
- Around line 47-55: Update the applyNumericVerification references in the
hazard analysis to link to its actual definition in src/lib/answer-verification
and its invocation in src/lib/rag/rag.ts around the cited call-site range,
replacing the incorrect rag.ts definition and outcome line links. Keep the
surrounding behavior description unchanged.
In `@docs/rag-injection-threat-model.md`:
- Around line 15-38: Update the documentation citations for buildRagSourceBlock
and its related prompt-field locations to reference the extracted
rag-source-block.ts module, including the sections at 70–86, 99–101, 112–125,
and 135–148. Retain rag.ts citations only for answerInstructions and
buildAnswerInput/answer-input assembly, and ensure all referenced line ranges
match the extracted implementation.
---
Nitpick comments:
In `@src/lib/rag/rag-query-guard.ts`:
- Around line 19-34: Extract the shared classification logic from
shouldShortCircuitUnsupportedSearch and isUnsupportedSoftTailAnalysis into a
single private helper that distinguishes pattern-guard matches from soft-tail
eligibility. Update both exported functions to reuse that helper while
preserving their current behavior: the first should short-circuit on any guard
or soft-tail match, and the second should return true only for the soft-tail
match.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: f344ebf5-2be1-48d1-81e6-9faf55e28cda
📒 Files selected for processing (114)
docs/clinical-hazard-analysis.mddocs/codebase-index.mddocs/deployment-architecture.mddocs/maturity-backlog-workorders.mddocs/observability-slos.mddocs/openai-cross-border-basis.mddocs/privacy-impact-assessment.mddocs/process-hardening.mddocs/rag-hybrid-findings-and-todo.mddocs/rag-injection-threat-model.mddocs/redesign/06-verification.mddocs/search-rag-master-context.mddocs/search-rag-master-plan.mddocs/tenancy-defense-in-depth-review.mdscripts/check-maintainability-budgets.mjsscripts/eval-answer-quality.tsscripts/eval-quality.tsscripts/eval-rag.tsscripts/eval-retrieval.tsscripts/eval-search-api.tsscripts/eval-search.tsscripts/eval-utils.tsscripts/warm-retrieval-cache.tssrc/app/api/answer/route.tssrc/app/api/answer/stream/route.tssrc/app/api/documents/[id]/labels/route.tssrc/app/api/documents/[id]/reviews/route.tssrc/app/api/documents/[id]/route.tssrc/app/api/documents/[id]/summarize/route.tssrc/app/api/documents/[id]/table-facts/route.tssrc/app/api/documents/bulk/reindex/route.tssrc/app/api/documents/bulk/route.tssrc/app/api/search/route.tssrc/components/clinical-dashboard/display-text.tssrc/lib/answer-verification.tssrc/lib/clinical-safety.tssrc/lib/cross-document-synthesis.tssrc/lib/rag/rag-answer-support.tssrc/lib/rag/rag-answer-text.tssrc/lib/rag/rag-cache-utils.tssrc/lib/rag/rag-cache.tssrc/lib/rag/rag-candidate-sources.tssrc/lib/rag/rag-claim-support.tssrc/lib/rag/rag-comparison.tssrc/lib/rag/rag-context-selection.tssrc/lib/rag/rag-contracts.tssrc/lib/rag/rag-document-summary-context.tssrc/lib/rag/rag-eval-cases.tssrc/lib/rag/rag-eval-diagnostics.tssrc/lib/rag/rag-extractive-answer.tssrc/lib/rag/rag-provider.tssrc/lib/rag/rag-query-guard.tssrc/lib/rag/rag-quote-verification.tssrc/lib/rag/rag-retrieval-variants.tssrc/lib/rag/rag-route-budget.tssrc/lib/rag/rag-routing.tssrc/lib/rag/rag-source-block.tssrc/lib/rag/rag-versioning.tssrc/lib/rag/rag.tssrc/lib/semantic-rerank.tssrc/lib/universal-search.tstests/anonymous-answer-cache-policy.test.tstests/answer-prose-runons.test.tstests/answer-ranking.test.tstests/answer-responsiveness-gate.test.tstests/api-validation-contract.test.tstests/architecture-boundaries.test.tstests/corpus-grounding.test.tstests/cross-tenant-staging-config.test.tstests/document-admin-rate-limit.test.tstests/document-mutation-routes.test.tstests/eval-utils.test.tstests/extractive-answer-formatting.test.tstests/private-access-routes.test.tstests/private-rag-access.test.tstests/public-access-deep.test.tstests/rag-abort-signal.test.tstests/rag-answer-fallback.test.tstests/rag-answer-support.test.tstests/rag-answer-text.test.tstests/rag-cache-invalidation.test.tstests/rag-cache-utils.test.tstests/rag-chunk-load-cache.test.tstests/rag-claim-support.test.tstests/rag-classifier-memo.test.tstests/rag-comparison.test.tstests/rag-content-accuracy.test.tstests/rag-context-budget.test.tstests/rag-document-summary.test.tstests/rag-eval-cases.test.tstests/rag-eval-source-governance.test.tstests/rag-fast-path-ordering.test.tstests/rag-generation-fingerprint.test.tstests/rag-injection.test.tstests/rag-offline-answer.test.tstests/rag-provider.test.tstests/rag-query-concurrency.test.tstests/rag-route-budget.test.tstests/rag-routing.test.tstests/rag-score.test.tstests/rag-second-stage-ranking.test.tstests/rag-shared-cache.test.tstests/rag-tail-latency.test.tstests/rag-trust.test.tstests/rag-variant-early-exit.test.tstests/railway-config.test.tstests/retrieval-access-scope.test.tstests/retrieval-hydration-scope.test.tstests/retrieval-query-variants.test.tstests/semantic-rerank.test.tstests/source-backed-recovery-cross-reference.test.tstests/source-review-route.test.tstests/universal-search.test.tsworker/main.ts
Summary
Phase 4 of the maturity backlog (
docs/maturity-backlog-workorders.md→ X2): the first real domain directory undersrc/lib, and the seam that unblocks directory-scoped boundary rules for the rest of the 197-file flat lib.rag.ts+ 21rag-*.ts) intosrc/lib/rag/viagit mv(renames preserved).@/lib/rag*→@/lib/rag/rag*(51 sites) and the relative../src/lib/rag*→../src/lib/rag/rag*(worker + tests). The../scripts/rag-offline-contract.mjsimport was deliberately left untouched.readFileSynccontract-test paths,docs/codebase-index.md, and rag path references across 13 maintained docs.Pure moves + path rewrites — no logic change, so behaviour is identical.
Verification
Full local gate, all green (run as constituent commands rather than the
verify:pr-localwrapper):npm run typecheck— pass.npm run test— 3012 pass; the only failure is the pre-existing container-onlypdf-extraction-budgetflake (a Python-subprocess deadline test with no rag dependency), which fails identically on cleanorigin/main— not a regression from this refactor.npm run lint— pass.npm run check:maintainability-budgets— pass (src/lib/rag/rag.ts5143/5238).npm run docs:check-index— pass (newsrc/lib/rag/indexed);npm run docs:check-links— pass (989 refs);npm run format:check— pass.display-text.ts, is a string helper — no JSX/markup).Risk and rollout
git log --followtraces history through the renames.Clinical Governance Preflight
This is a byte-identical relocation of the rag modules (
git mv+ import-path rewrites); no clinical behaviour, data flow, or configuration changed. Each item is preserved by construction:Clinical KB Database(sjrfecxgysukkwxsowpy)Notes
Next natural step (separate PR) is X3 — decompose
rag.tsbehind the maintainability budget, now that its siblings already sit insrc/lib/rag/. This PR intentionally does not touch logic.Generated by Claude Code
Summary by CodeRabbit